package com.nuumoblie.bluetoothtools.bt;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.nuumoblie.bluetoothtools.utils.Utils;

import java.util.UUID;


/**
 * 服务端监听和连接线程，只连接一个设备
 */
public class BtOptServer extends BtOptBase {
    private static final String TAG = BtOptServer.class.getSimpleName();
    private BluetoothServerSocket mSSocket;
    private boolean isMatch = false;
    private boolean isListen = false;

    public boolean isListen() {
        return isListen;
    }

    BtOptServer(Listener listener) {
        super(listener);
//        listen();
    }

    public void setMatch(boolean isMatch) {
        this.isMatch = isMatch;
    }


    /**
     * 监听客户端发起的连接
     */
    public synchronized String listen() {
        String uuid = "";
        try {
            isListen = true;

            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (isMatch) {
                UUID secure = UUID.randomUUID();
                Log.v("lmjssjj", "listenUsingRfcommWithServiceRecord");
                mSSocket = adapter.listenUsingRfcommWithServiceRecord(TAG, secure); //加密传输，Android强制执行配对，弹窗显示配对码
                uuid = secure.toString();
            } else {
                UUID normoal = UUID.randomUUID();
                Log.v("lmjssjj", "listenUsingInsecureRfcommWithServiceRecord");
                mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(TAG, normoal); //明文传输(不安全)，无需配对
                uuid = normoal.toString();
            }
//            mSSocket = adapter.listenUsingRfcommWithServiceRecord(TAG, SPP_UUID); //加密传输，Android强制执行配对，弹窗显示配对码
//            mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(TAG, SPP_UUID); //明文传输(不安全)，无需配对
            // 开启子线程
            Utils.EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        BluetoothSocket socket = mSSocket.accept(); // 监听连接
                        mSSocket.close(); // 关闭监听，只连接一个设备
                        loopRead(socket); // 循环读取
                    } catch (Throwable e) {
                        e.printStackTrace();
                        close();
                    }
                }
            });
        } catch (Throwable e) {
            e.printStackTrace();
            close();
        }
        return uuid;
    }

    @Override
    public void close() {
        super.close();
        isListen = false;
        try {
            if (mSSocket != null) {
                mSSocket.close();
                mSSocket = null;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void unListen() {
        close();
    }
}